<template>
  <el-select ref="select" :value="value" :multiple="multiple" clearable filterable remote :remote-method="remoteMethod"
             :reserve-keyword="true" default-first-option :placeholder="$tt('tip_input_key')" :loading="loading" v-bind="$attrs"
             v-on="$listeners" @input="input">
    <el-option v-for="item in options" :key="item.id" :label="option.label(item)" :value="item[option.value]">
    </el-option>
  </el-select>

</template>

<script>
export default {
  name: "fms-subject-choose",
  data() {
    return {
      options: [],
      loading: false,
      remoteQuery: "",
      option: { label: item => this.$formatNameCode(item.subjectCode, item.subjectName), value: 'id' },
    }
  },
  props: {
    value: null,
    currentLabel: "",
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    currentLabel: function (val) {
      this.$nextTick(() => {
        this.$refs.select.selectedLabel = val
      })
    },
    remoteQuery: function (newVal) {
      this.remoteNet(newVal)
    }
  },
  mounted() {
    this.remoteNet()
    if (this.currentLabel) {
      this.$nextTick(() => {
        this.$refs.select.selectedLabel = this.currentLabel
      })
    }
  },
  methods: {
    focus(e) {
      this.remoteQuery = ""
    },

    input(e) {
      const item = _.find(this.options, it => it[this.option.value] == e)
      this.$emit('changeItem', item)
    },

    remoteMethod: _.debounce(function (query) {
      this.remoteQuery = query ? query : ""
    }, 700),
    remoteNet(query) {

      let data = {}
      if (query) data.keyword = query.trim()
      this.loading = true
      this.$ajax({
        url: "/fms-api/agent/AgentSubjectRpc/select.json",
        method: 'post',
        data,
        tip: false,
        success: (res) => {
          if (res.data.rows) this.options = res.data.rows
        },
        failure: () => {
          this.options = []
        },
        complete: () => {
          this.loading = false
        }
      })
    },
  },

}
</script>

<style>

</style>
